package finalize

import (
	"log"
	"sync"
	"time"

	"xp/lib/md"
	"xp/lib/utils"
)

var (
	mu     sync.Mutex
	cleans = make([]func(chan error), 0)
)

func OnExit(fns ...func() error) {
	mu.Lock()
	defer mu.Unlock()

	for _, fn := range fns {
		f := fn
		cleans = append(cleans, func(chan error) {
			if err := f(); err != nil {
				log.Println(err)
			}
		})
	}
}

func Exit() {
	mu.Lock()
	defer mu.Unlock()

	log.Printf("shutting down, service up time %s\n", time.Since(md.Get().State.UpAt))
	<-utils.Go(cleans...)
}
